package com.yuexun.beilunpatient.ui.registration.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yuexun.beilunpatient.R;
import com.yuexun.beilunpatient.base.BaseEntity;
import com.yuexun.beilunpatient.base.BaseKJActivity;
import com.yuexun.beilunpatient.config.AppConfig;
import com.yuexun.beilunpatient.config.Constants;
import com.yuexun.beilunpatient.ui.registration.bean.AppointmentHistoryDetailBean;
import com.yuexun.beilunpatient.ui.registration.bean.AppointmentPayBean;
import com.yuexun.beilunpatient.ui.registration.bean.PayReqBean;
import com.yuexun.beilunpatient.ui.registration.model.impl.RegistrationModel;
import com.yuexun.beilunpatient.ui.registration.model.impl.RegistrationPayModel;
import com.yuexun.beilunpatient.ui.registration.presenter.impl.AppointmentCancelPresenter;
import com.yuexun.beilunpatient.ui.registration.presenter.impl.AppointmentDetailPresenter;
import com.yuexun.beilunpatient.ui.registration.presenter.impl.AppointmentPayPresenter;
import com.yuexun.beilunpatient.ui.registration.ui.view.IAppointmentCancelView;
import com.yuexun.beilunpatient.ui.registration.ui.view.IAppointmentDetailView;
import com.yuexun.beilunpatient.ui.registration.ui.view.IAppointmentPayView;
import com.yuexun.beilunpatient.utils.PayResult;
import com.yuexun.beilunpatient.widget.ClickDialog;
import com.yuexun.beilunpatient.widget.LoadingDialog;

import org.json.JSONException;
import org.json.JSONObject;
import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by chenss on 2018/10/23.
 */
public class Act_Registration_Detail extends BaseKJActivity implements IAppointmentDetailView, IAppointmentCancelView, IAppointmentPayView {

    @Bind(R.id.tv_num)
    TextView tvNum;
    @Bind(R.id.tv_hos)
    TextView tvHos;
    @Bind(R.id.tv_department)
    TextView tvDepartment;
    @Bind(R.id.doc_name)
    TextView docName;
    @Bind(R.id.tv_date)
    TextView tvDate;
    @Bind(R.id.tv_time)
    TextView tvTime;
    @Bind(R.id.tv_regfee)
    TextView tvRegfee;
    @Bind(R.id.tv_fee)
    TextView tvFee;
    @Bind(R.id.tv_regtime)
    TextView tvRegtime;
    @Bind(R.id.tv_code)
    TextView tvCode;
    @Bind(R.id.tv_state)
    TextView tvState;
    @Bind(R.id.tv_cancel)
    TextView tvCancel;
    @Bind(R.id.tv_pay)
    TextView tvPay;
    @Bind(R.id.ll_zhifubao)
    LinearLayout llZhifubao;
    @Bind(R.id.ll_weixin)
    LinearLayout llWeixin;
    @Bind(R.id.iv_zhifubao)
    ImageView ivZhifubao;
    @Bind(R.id.iv_weixin)
    ImageView ivWeixin;

    AppointmentPayPresenter payPresenter;
    AppointmentHistoryDetailBean detailBean;
    AppointmentDetailPresenter presenter;
    AppointmentCancelPresenter cancelPresenter;
    LoadingDialog dialog;
    String scheduleGhxh;
    String scheduleDate;
    boolean isWeixin;

    private IWXAPI msgApi;
    private static final int SDK_PAY_FLAG = 1;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_registration_detail);
        ButterKnife.bind(this);        // Here, thisActivity is the current activity

    }

    /**
     * 获取权限使用的 RequestCode
     */
    private static final int PERMISSIONS_REQUEST_CODE = 1002;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        requestPermission();
    }

    /**
     * 检查支付宝 SDK 所需的权限，并在必要的时候动态获取。
     * 在 targetSDK = 23 以上，READ_PHONE_STATE 和 WRITE_EXTERNAL_STORAGE 权限需要应用在运行时获取。
     * 如果接入支付宝 SDK 的应用 targetSdk 在 23 以下，可以省略这个步骤。
     */
    private void requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{
                            Manifest.permission.READ_PHONE_STATE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                    }, PERMISSIONS_REQUEST_CODE);

        } else {
            ViewInject.toast("支付宝 SDK 已有所需的权限");
        }
    }

    /**
     * 权限获取回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSIONS_REQUEST_CODE: {

                // 用户取消了权限弹窗
                if (grantResults.length == 0) {
                    ViewInject.toast("无法获取支付宝 SDK 所需的权限, 请到系统设置开启");
                    return;
                }

                // 用户拒绝了某些权限
                for (int x : grantResults) {
                    if (x == PackageManager.PERMISSION_DENIED) {
                        ViewInject.toast("无法获取支付宝 SDK 所需的权限, 请到系统设置开启");
                        return;
                    }
                }

                // 所需的权限均正常获取
                ViewInject.toast("支付宝 SDK 所需的权限已经正常获取");
            }
        }
    }

    @Override
    public void initData() {
        presenter = new AppointmentDetailPresenter(new RegistrationModel(), this);
        cancelPresenter = new AppointmentCancelPresenter(new RegistrationModel(), this);
        payPresenter = new AppointmentPayPresenter(new RegistrationPayModel(), this);
        scheduleGhxh = getIntent().getExtras().getString("scheduleGhxh");
        scheduleDate = getIntent().getExtras().getString("scheduleDate");

//        getAppointentDetail();

//        dialog = new LoadingDialog(aty);
//        dialog.show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getAppointentDetail();

        dialog = new LoadingDialog(aty);
        dialog.show();
    }

    private void getAppointentDetail(){
        Map<String, String> params = new HashMap<>();
        params.put("accessToken", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.ACCESSTOKEN));
        params.put("memberNumProxy", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.MEMBENUM));
        params.put("scheduleGhxh", scheduleGhxh);
        params.put("scheduleDate", scheduleDate);
        params.put("memberNum", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.MEMBENUMPROXY));
        params.put("sessionUuidPatient", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        presenter.getAppointentDetail(params);
    }

    private void initView(){
        tvNum.setText(detailBean.getReg_num());
        tvHos.setText(detailBean.getHospital_name());
        tvDepartment.setText(detailBean.getDepartment_name());
        docName.setText(detailBean.getDoctor_name());
        tvDate.setText(detailBean.getSchedule_date());
        if(detailBean.getOut_time().equals("A")){
            tvTime.setText("上午");
        }else if(detailBean.getOut_time().equals("P")){
            tvTime.setText("下午");
        }else if(detailBean.getOut_time().equals("F")){
            tvTime.setText("全天");
        }else if(detailBean.getOut_time().equals("N")){
            tvTime.setText("夜间");
        }
        tvRegfee.setText(detailBean.getReg_fee());
        tvFee.setText(detailBean.getClinic_fee());
        tvRegtime.setText(detailBean.getYysjd());
        if(detailBean.getRes_type().equals("2")){
            tvState.setText("未支付");
            tvCancel.setVisibility(View.VISIBLE);
            tvPay.setVisibility(View.VISIBLE);
            llZhifubao.setVisibility(View.VISIBLE);
            llWeixin.setVisibility(View.VISIBLE);
        }else if(detailBean.getRes_type().equals("3")){
            tvState.setText("未成功");
            tvCancel.setVisibility(View.GONE);
            tvPay.setVisibility(View.GONE);
            llZhifubao.setVisibility(View.GONE);
            llWeixin.setVisibility(View.GONE);
        }else if(detailBean.getRes_type().equals("4")){
            tvState.setText("已退号");
            tvCancel.setVisibility(View.GONE);
            tvPay.setVisibility(View.GONE);
            llZhifubao.setVisibility(View.GONE);
            llWeixin.setVisibility(View.GONE);
        }else if(detailBean.getRes_type().equals("5")){
            tvState.setText("已完成");
            tvCancel.setVisibility(View.VISIBLE);
            tvPay.setVisibility(View.GONE);
            llZhifubao.setVisibility(View.GONE);
            llWeixin.setVisibility(View.GONE);
        }
        tvCode.setText(detailBean.getQhyzm());
    }

    private void ApiForKjHttp(AppointmentPayBean payBean) {
//        Map<String, String> params = new HashMap<>();
//        params.put("payNum", payBean.getPay_num());
//        params.put("phoneNo", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.PHONE));
//        if(isWeixin){
//            params.put("channelType", "2");//2微信 3支付宝 4微信公众号
//        }else{
//            params.put("channelType", "3");//2微信 3支付宝 4微信公众号
//        }
//        params.put("payMoney", (int) (Double.valueOf(payBean.getPay_money()) * 100) + "");
//        params.put("sessionUuidPatient", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
//        payPresenter.generatePayOrder(params);

        //生成预约挂号支付订单号
        String BaseUrl = AppConfig.WEB_ROOT_PAY + "generatePayOrder.json?";

        KJHttp client = new KJHttp();
        HttpParams params = new HttpParams();
        params.put("payNum", payBean.getPay_num());
        params.put("phoneNo", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.PHONE));
        if(isWeixin){
            params.put("channelType", "2");//2微信 3支付宝 4微信公众号
        }else{
            params.put("channelType", "3");//2微信 3支付宝 4微信公众号
        }
        params.put("payMoney", (int) (Double.valueOf(payBean.getPay_money()) * 100) + "");
        params.put("sessionUuidPatient", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));

        client.post(BaseUrl, params, new HttpCallBack() {
            @Override
            public void onSuccess(String t) {
                super.onSuccess(t);
                dialog.dismiss();
                PayReqBean baseBean = JSON.parseObject(t, PayReqBean.class);
                if (baseBean.getCode().equals("1")) {
                    ViewInject.toast("生成预约挂号支付订单号成功");
                    PreferenceHelper.write(aty, AppConfig.USER_INFO, AppConfig.SENDTN, baseBean.getSendTn());
                    final String ss = baseBean.getResult().getPayOrderResp();
                    if (isWeixin) {
                        msgApi = WXAPIFactory.createWXAPI(aty, Constants.APP_ID);
                        msgApi.registerApp(Constants.APP_ID);
                        try {
                            JSONObject json = new JSONObject(ss);
                            PayReq request = new PayReq();
                            request.appId = json.getString("appid");
                            request.partnerId = json.getString("partnerid");
                            request.prepayId = json.getString("prepayid");
                            request.packageValue = json.getString("packagevalue");
                            request.nonceStr = json.getString("noncestr");
                            request.timeStamp = json.getString("timestamp");
                            request.sign = json.getString("sign");
                            msgApi.sendReq(request);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Runnable payRunnable = new Runnable() {

                            @Override
                            public void run() {
                                PayTask alipay = new PayTask(aty);
                                Map<String, String> result = alipay.payV2(ss, true);

                                Message msg = new Message();
                                msg.what = SDK_PAY_FLAG;
                                msg.obj = result;
                                mHandler.sendMessage(msg);
                            }
                        };
                        // 必须异步调用
                        Thread payThread = new Thread(payRunnable);
                        payThread.start();

                    }
                }else {
                    ViewInject.toast("生成预约挂号支付订单号失败");
                }
            }

            @Override
            public void onFailure(int errorNo, String strMsg) {
                super.onFailure(errorNo, strMsg);
                dialog.dismiss();
                Toast.makeText(aty, "生成预约挂号支付订单号失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    String codeValue = "";
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        ViewInject.toast("支付成功: " + payResult);
                        codeValue = "支付成功";
//                        getAppointentDetail();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        ViewInject.toast("支付失败: " + payResult);
                        codeValue = "支付失败";
                    }
                    Intent intent = new Intent(aty, Act_Registration_Result.class);
                    intent.putExtra("result", codeValue);
                    startActivity(intent);
//                    finish();

                    break;
                default:
                    break;
            }
        };
    };

    @OnClick({R.id.title_back, R.id.tv_cancel, R.id.tv_pay, R.id.ll_zhifubao, R.id.ll_weixin})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.tv_cancel:
                final ClickDialog clickDialog = new ClickDialog(aty).builder().setTxt("确认退号");
                clickDialog.setCallBack(new ClickDialog.ICallBack() {
                    @Override
                    public void callback(Bundle bundle) {
                        Map<String, String> params = new HashMap<>();
                        params.put("thlyfd", "5");
                        params.put("accessToken", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.ACCESSTOKEN));
                        params.put("memberNumProxy", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.MEMBENUM));
                        params.put("scheduleGhxh", scheduleGhxh);
                        params.put("scheduleDate", scheduleDate);
                        params.put("memberNum", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.MEMBENUMPROXY));
                        params.put("sessionUuidPatient", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
                        cancelPresenter.cancelAppoinment(params);
                        clickDialog.dismiss();
                        dialog.show();
                    }
                });
                clickDialog.show();
                break;
            case R.id.tv_pay:
                Map<String, String> params = new HashMap<>();
                if(isWeixin){
                    params.put("payChannel", "3006");//3006=微信，3009=支付宝
                }else{
                    params.put("payChannel", "3009");//3006=微信，3009=支付宝
                }
                params.put("accessToken", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.ACCESSTOKEN));
                params.put("memberNumProxy", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.MEMBENUM));
                params.put("scheduleGxh", scheduleGhxh);
                params.put("scheduleDate", scheduleDate);
                params.put("memberNum", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.MEMBENUMPROXY));
                params.put("sessionUuidPatient", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
                presenter.toPayAppoinment(params);
                dialog.show();
                break;
            case R.id.ll_zhifubao:
                ivZhifubao.setBackgroundResource(R.drawable.select_checked);
                ivWeixin.setBackgroundResource(R.drawable.select_unchecked);
                isWeixin = false;
                break;
            case R.id.ll_weixin:
                ivZhifubao.setBackgroundResource(R.drawable.select_unchecked);
                ivWeixin.setBackgroundResource(R.drawable.select_checked);
                isWeixin = true;
                break;
        }
    }

    @Override
    public void getAppointentDetail(BaseEntity<AppointmentHistoryDetailBean> baseEntity) {
        dialog.dismiss();
        if(baseEntity.getStatus().equals("200")){
            detailBean = baseEntity.getDatas().get(0);
            initView();
        }
    }

    @Override
    public void toPayAppoinment(BaseEntity<AppointmentPayBean> baseEntity) {
        if(baseEntity.getStatus().equals("200")){
            AppointmentPayBean payBean = baseEntity.getDatas().get(0);
            ApiForKjHttp(payBean);
        }else{
            ViewInject.toast(baseEntity.getMessage());
            dialog.dismiss();
        }
    }

    @Override
    public void cancelAppoinment(BaseEntity<String> baseEntity) {
        dialog.dismiss();
        if(baseEntity.getStatus().equals("200")){
            finish();
        }
    }

    @Override
    public void generatePayOrder(String s) {

    }
}
